package impl.gui.listeners;

import impl.core.UDecideManager;
import impl.gui.util.ChoiceCellRenderer;
import impl.reasoning.UDecideReasoner;
import impl.util.UtilityAssertion;

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.HashSet;

import javax.swing.JList;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import org.semanticweb.owlapi.model.OWLNamedIndividual;

public class UtilityAssertionListListener extends MouseAdapter implements ListSelectionListener {

	private JList<UtilityAssertion>	uAssertionList;

	public UtilityAssertionListListener(JList<UtilityAssertion> uAssertionList) {
		this.uAssertionList = uAssertionList;
	}

	@Override
	public void valueChanged(ListSelectionEvent e) {
		if (e.getValueIsAdjusting()) { // selecting is still done
			return;
		} else if (this.uAssertionList.getSelectedIndex() == -1) {
			UDecideManager.getInstance().getGUI().setChoiceCellRenderer(new ChoiceCellRenderer());
			UDecideManager.getInstance().getGUI().utilityAssertionSelected(false);
		} else {
			UDecideManager.getInstance().getGUI().utilityAssertionSelected(true);

			UDecideManager.getInstance().getGUI().clearChoiceSelection();

			UDecideReasoner rea = UDecideManager.getInstance().getUDecideReasoner();

			if (rea != null) { // calculation has been done
				HashSet<OWLNamedIndividual> indisToColor = new HashSet<OWLNamedIndividual>();

				boolean firstInsertion = true;

				for (UtilityAssertion u : this.uAssertionList.getSelectedValuesList()) {
					if (firstInsertion) {
						indisToColor.addAll(rea.getSatisfyingChoicesForUtilityAssertion(u));
						firstInsertion = false;
					} else {
						indisToColor.retainAll(rea.getSatisfyingChoicesForUtilityAssertion(u));
					}
				}

				UDecideManager.getInstance().getGUI().setChoiceCellRenderer(new ChoiceCellRenderer(indisToColor));
			}
		}
	}

	@Override
	public void mouseClicked(MouseEvent e) {
		JList<UtilityAssertion> list = (JList<UtilityAssertion>) e.getSource();
		if (e.getClickCount() == 2) {
			UtilityAssertion oldUtilityAssertion = list.getModel().getElementAt(list.locationToIndex(e.getPoint()));
			UDecideManager.getInstance().getGUI().showEditUtilityAssertionDialog(oldUtilityAssertion);
		}
	}
}
